const log = require('../util/log')
const config = require('../util/config')
const chromeMng = require('../mng/chromeMng')

module.exports = (req, res) => {
  require('../util/service').handlePost(req, res, async (reqObj, resolve) => {
    if (!reqObj.keyword) {
      resolve({
        result: -1,
        msg: '缺少keyword'
      })
      return
    }
    if (config.domain == '') {
      chromeMng.getJdItems({
        keyword: reqObj.keyword
      }).then(list => {
        resolve({
          list: list
        })
      }, result => {
        log(result)
        resolve({
          result: -1,
          msg: result
        })
      })
    } else if (config.domain == 'zoro.site') {
      require('../util/getHtml')({
        url: require('../mng/chromeServerMng').get() + 'getJdItem.do',
        data: JSON.stringify(reqObj)
      }).then(result => {
        var obj = JSON.parse(result)
        if (obj.result == -1) {
          resolve(obj)
          return
        }
        var promises = []
        obj.list.forEach(item => {
          promises.push(new Promise(resolve => {
            item.rate = Math.round(item.rate * config.returnRate * 100) / 100
            const mongoMng = require('../mng/mongoMng')
            if (!mongoMng.db) {
              resolve()
              return
            }
            mongoMng.db.collection('item').find({
              link: item.link,
            }).toArray((err, result) => {
              if (err) {
                log(err);
                return;
              }
              if (result.length > 0 && result[0].advLink && result[0].advLink != -1) {
                item.advLink = result[0].advLink
              }
              resolve()
            })
          }))
        })
        Promise.all(promises).then(result => {
          resolve(obj)
        }, result => {
          log(result)
          resolve({
            result: -1,
            msg: '系统错误'
          })
        })
      })
    }
  })
}
